package com.pachong.android.framework.httprequest.volleyadaptee;

import android.text.TextUtils;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyLog;
import com.pachong.android.framework.httprequest.UrlParams;

import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MultipartPostRequest extends Request<String> {

    private MultipartEntity entity = new MultipartEntity();

    private final Listener<String> mListener;
    private UrlParams mRequestParams;
    private Map<String, String> mHeaderParams;

    /**
     * 多个文件，对应一个key
     *
     * @param errorListener
     * @param listener
     */
    public MultipartPostRequest(String url, UrlParams reqParams, Map<String, String> header, Listener<String> listener, ErrorListener errorListener) {
        super(Method.POST, url, errorListener);
        mListener = listener;
        mRequestParams = reqParams;
        mHeaderParams = header;
        buildMultipartEntity();
    }

    private void buildMultipartEntity() {

        if(mRequestParams != null) {
            List<UrlParams.FileWrapper> files = mRequestParams.getFileParamList();
            if (files != null && files.size() > 0) {
                for (UrlParams.FileWrapper fileWrapper : files) {
                    if (TextUtils.isEmpty(fileWrapper.contentType)) {
                        entity.addPart(fileWrapper.fileKey, new FileBody(fileWrapper.file));

                    } else {
                        entity.addPart(fileWrapper.fileKey, new FileBody(fileWrapper.file, fileWrapper.contentType));
                    }


                }
            }
        }


        try {
            if (mRequestParams != null && mRequestParams.getUrlParamMap().size() > 0) {
                for (Map.Entry<String, String> entry : mRequestParams.getUrlParamMap().entrySet()) {
                    entity.addPart(entry.getKey(), new StringBody(entry.getValue(), Charset.forName("UTF-8")));
                }
            }
        } catch (UnsupportedEncodingException e) {
            VolleyLog.e("UnsupportedEncodingException");
        }

    }

    @Override
    public String getBodyContentType() {
        Log.e("vivi", "  entity.getContentType()  " + entity.getContentType().getValue());
        return entity.getContentType().getValue();
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            entity.writeTo(bos);
        } catch (IOException e) {
            VolleyLog.e("IOException writing to ByteArrayOutputStream");
        }
        return bos.toByteArray();
    }


    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        return ResponseHelper.parseNetworkResponse2String(response);
    }


    @Override
    public Map<String, String> getHeaders() {
        HashMap<String, String> headers = new HashMap<String, String>();
//        headers.put("Content-Type", "application/json; charset=UTF-8"); // 不可以覆盖Content-Type
        headers.put("Accept-Encoding", "gzip, deflate");
        headers.put("Accept", "application/json");
        if (mHeaderParams != null && mHeaderParams.size() > 0) {
            headers.putAll(mHeaderParams);
        }
        return headers;
    }

    @Override
    protected void deliverResponse(String response) {
        mListener.onResponse(response);
    }
}